package uestc.lj.gulishop.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import uestc.lj.common.utils.PageUtils;
import uestc.lj.common.utils.Query;

import uestc.lj.gulishop.product.dao.CategoryDao;
import uestc.lj.gulishop.product.entity.CategoryEntity;
import uestc.lj.gulishop.product.service.CategoryBrandRelationService;
import uestc.lj.gulishop.product.service.CategoryService;
import uestc.lj.gulishop.product.vo.Catelog2VO;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查出所有分类以及子分类，以树形结构组装起来
     *
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(null);
        // 2.组装成父子的树形结构
        // 2.1 找到所有的一级分类
        List<CategoryEntity> level1List = categoryEntityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu, categoryEntityList));
                    return menu;
                })
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());

        return level1List;
    }

    /**
     * 批量删除未被引用的菜单
     *
     * @param asList
     */
    @Override
    public void removeMenusByIds(List<Long> asList) {
        // TODO 判断当前菜单是否被引用

        // 删除
        baseMapper.deleteBatchIds(asList);

    }

    /**
     * 根据当前菜单ID求解出当前菜单的完整路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentCatelogPath = findParentCatelogPath(catelogId, paths);
        Collections.reverse(parentCatelogPath);
        return parentCatelogPath.toArray(new Long[parentCatelogPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     *
     * @param category
     */
    @Override
    @Transactional
/*    @Caching(evict = {
            @CacheEvict(cacheNames = {"category"}, key = "'getLevelOneCategory'"),
            @CacheEvict(cacheNames = {"category"}, key = "'getCatalogJson'")
    })*/
    @CacheEvict(cacheNames = {"category"}, allEntries = true)
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);

        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * 查询所有一级分类，用于前端页面展示
     *
     * @return
     */
    @Override
    @Cacheable(cacheNames = {"category"}, key = "#root.methodName",sync = true)
    public List<CategoryEntity> getLevelOneCategory() {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_cid", 0);

        return baseMapper.selectList(wrapper);
    }

    @Override
    @Cacheable(cacheNames = {"category"}, key = "#root.methodName",sync = true)
    public Map<String, List<Catelog2VO>> getCatalogJson() {

        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 1.查询所有一级分类
        List<CategoryEntity> levelOneCategory = getParent_cid(selectList, 0L);
        // 2.封装数据
        Map<String, List<Catelog2VO>> map = levelOneCategory.stream()
                .collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    // 查询当前一级分类对应的二级分类
                    List<CategoryEntity> categoryEntityList = getParent_cid(selectList, v.getCatId());
                    // 进行对应对象的封装
                    List<Catelog2VO> catelog2VOS = null;
                    if (categoryEntityList != null) {
                        catelog2VOS = categoryEntityList.stream().map(l2 -> {
                            Catelog2VO catelog2VO = new Catelog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            // 找当前二级分类的三级分类并封装成vo
                            List<CategoryEntity> cateloglevel3VO = getParent_cid(selectList, l2.getCatId());
                            if (cateloglevel3VO != null) {
                                List<Catelog2VO.Catelog3VO> catelog3VOS = cateloglevel3VO.stream().map(l3 -> {
                                    Catelog2VO.Catelog3VO catelog3VO = new Catelog2VO.Catelog3VO(l3.getCatId().toString(), l3.getName(), l2.getCatId().toString());
                                    return catelog3VO;
                                }).collect(Collectors.toList());
                                catelog2VO.setCatalog3List(catelog3VOS);
                            }
                            return catelog2VO;
                        }).collect(Collectors.toList());
                    }
                    return catelog2VOS;
                }));
        return map;
    }

    /**
     * 使用redis作为缓存
     * TODO 产生堆外内存溢出：OutOfDirectMemoryError
     * springboot2.0之后默认使用lettuce作为操作redis的客户端。它使用netty进行网络通信
     * lettuce的bug导致netty堆外内存溢出————可以通过-Dio.netty.maxDirectMemory进行设置
     * 目前解决的方案是切换使用jedis
     *
     * @return
     */
    public Map<String, List<Catelog2VO>> getCatalogJsonOld() {

        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {

            // 缓存中没有，则查询数据库，同时要实现防止缓存击穿
            Map<String, List<Catelog2VO>> catalogJsonFromDB = getCatalogJsonFromDBWithRedissonLock();
            // 防止缓存穿透
            if (catalogJsonFromDB == null) {
                stringRedisTemplate.opsForValue().set("catalogJSON", "0", 7, TimeUnit.DAYS);
            }
            return catalogJsonFromDB;
        }

        // 缓存中有则直接返回反序列化的对象
        return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2VO>>>() {
        });
    }

    /**
     * 使用分布式锁框架redisson
     *
     * @return
     */
    public Map<String, List<Catelog2VO>> getCatalogJsonFromDBWithRedissonLock() {
        // 1.占取分布式锁
        RLock lock = redissonClient.getLock("catalogJson-lock");
        lock.lock(30, TimeUnit.SECONDS);
        Map<String, List<Catelog2VO>> catalogFromDB = null;
        // 分布式锁成功加锁
        try {
            catalogFromDB = getCatalogFromDB();
        } finally {
            lock.unlock();
        }
        return catalogFromDB;
    }

    public Map<String, List<Catelog2VO>> getCatalogJsonFromDBWithRedisLock() {
        // 使用redis分布式锁 ,设置锁的过期时间（将锁的过期时长设长一些，防止业务未执行完，锁过期，解决自动续期的问题），防止死锁,  设置锁的值唯一，防止误删操作
        String token = UUID.randomUUID().toString();
        Boolean ifAbsent = stringRedisTemplate.opsForValue().setIfAbsent("lock", token, 300, TimeUnit.SECONDS);

        while (ifAbsent) {

            Map<String, List<Catelog2VO>> catalogFromDB = null;
            // 分布式锁成功加锁
            try {
                catalogFromDB = getCatalogFromDB();
            } finally {
                // 判断是否是自己当时的锁----->问题：获取锁的value+删除锁的时长 > 锁的过期时长，导致误删别人的锁

//            if (token.equals(stringRedisTemplate.opsForValue().get("lock"))) {
//                stringRedisTemplate.delete("lock");
//            }

                // 应保证获取锁和删锁是原子操作 --->使用 lua脚本 进行删除锁
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Collections.singletonList("lock"), token);
            }
            return catalogFromDB;
        }
        System.out.println("为获取到分布式锁，等待重试");
        return getCatalogJsonFromDBWithRedisLock();
/*        if (ifAbsent) {
            Map<String, List<Catelog2VO>> catalogFromDB = null;
            // 分布式锁成功加锁
            try {
                catalogFromDB = getCatalogFromDB();
            } finally {
                // 判断是否是自己当时的锁----->问题：获取锁的value+删除锁的时长 > 锁的过期时长，导致误删别人的锁

//            if (token.equals(stringRedisTemplate.opsForValue().get("lock"))) {
//                stringRedisTemplate.delete("lock");
//            }

                // 应保证获取锁和删锁是原子操作 --->使用 lua脚本 进行删除锁
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<Integer>(script, Integer.class), Collections.singletonList("lock"), token);
            }
            return catalogFromDB;
        } else {
            // 加锁失败，需要重试
            try {
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDBWithRedisLock();
        }*/
    }

    /**
     * 从数据库中查询所有菜单，用于前端页面展示
     *
     * @return
     */
    public Map<String, List<Catelog2VO>> getCatalogJsonFromDBWithLocalLock() {
        //使用synchronized加锁
        synchronized (this) {
            // 双重检查使用缓存
            String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
            if (!StringUtils.isEmpty(catalogJSON)) {
                // 缓存不为空直接返回即可
                return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2VO>>>() {
                });
            }
            System.out.println("查询数据库!!!!");
            // 优化业务逻辑代码
            List<CategoryEntity> selectList = baseMapper.selectList(null);

            // 1.查询所有一级分类
            List<CategoryEntity> levelOneCategory = getParent_cid(selectList, 0L);
            // 2.封装数据
            Map<String, List<Catelog2VO>> map = levelOneCategory.stream()
                    .collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                        // 查询当前一级分类对应的二级分类
                        List<CategoryEntity> categoryEntityList = getParent_cid(selectList, v.getCatId());
                        // 进行对应对象的封装
                        List<Catelog2VO> catelog2VOS = null;
                        if (categoryEntityList != null) {
                            catelog2VOS = categoryEntityList.stream().map(l2 -> {
                                Catelog2VO catelog2VO = new Catelog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                                // 找当前二级分类的三级分类并封装成vo
                                List<CategoryEntity> cateloglevel3VO = getParent_cid(selectList, l2.getCatId());
                                if (cateloglevel3VO != null) {
                                    List<Catelog2VO.Catelog3VO> catelog3VOS = cateloglevel3VO.stream().map(l3 -> {
                                        Catelog2VO.Catelog3VO catelog3VO = new Catelog2VO.Catelog3VO(l3.getCatId().toString(), l3.getName(), l2.getCatId().toString());
                                        return catelog3VO;
                                    }).collect(Collectors.toList());
                                    catelog2VO.setCatalog3List(catelog3VOS);
                                }
                                return catelog2VO;
                            }).collect(Collectors.toList());
                        }
                        return catelog2VOS;
                    }));
            // 防止缓存穿透
            if (map == null) {
                stringRedisTemplate.opsForValue().set("catalogJSON", "0", 7, TimeUnit.DAYS);
            }
            // 提前再将数据转为json存入缓存中,原子操作，防止高并发多次查询数据库，锁不住的结果
            // 设置七天过期，防止缓存雪崩
            stringRedisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(map), 7, TimeUnit.DAYS);
            return map;
        }

    }

    /**
     * 从数据库中查询菜单并且封装成前端页面需要的菜单实体
     *
     * @return
     */
    private Map<String, List<Catelog2VO>> getCatalogFromDB() {
        // 双重检查使用缓存
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            // 缓存不为空直接返回即可
            return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2VO>>>() {
            });
        }
        // 优化业务逻辑代码
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        // 1.查询所有一级分类
        List<CategoryEntity> levelOneCategory = getParent_cid(selectList, 0L);
        // 2.封装数据
        Map<String, List<Catelog2VO>> map = levelOneCategory.stream()
                .collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                    // 查询当前一级分类对应的二级分类
                    List<CategoryEntity> categoryEntityList = getParent_cid(selectList, v.getCatId());
                    // 进行对应对象的封装
                    List<Catelog2VO> catelog2VOS = null;
                    if (categoryEntityList != null) {
                        catelog2VOS = categoryEntityList.stream().map(l2 -> {
                            Catelog2VO catelog2VO = new Catelog2VO(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            // 找当前二级分类的三级分类并封装成vo
                            List<CategoryEntity> cateloglevel3VO = getParent_cid(selectList, l2.getCatId());
                            if (cateloglevel3VO != null) {
                                List<Catelog2VO.Catelog3VO> catelog3VOS = cateloglevel3VO.stream().map(l3 -> {
                                    Catelog2VO.Catelog3VO catelog3VO = new Catelog2VO.Catelog3VO(l3.getCatId().toString(), l3.getName(), l2.getCatId().toString());
                                    return catelog3VO;
                                }).collect(Collectors.toList());
                                catelog2VO.setCatalog3List(catelog3VOS);
                            }
                            return catelog2VO;
                        }).collect(Collectors.toList());
                    }
                    return catelog2VOS;
                }));
        // 防止缓存穿透
        if (map == null) {
            stringRedisTemplate.opsForValue().set("catalogJSON", "0", 7, TimeUnit.DAYS);
        }
        // 提前再将数据转为json存入缓存中,原子操作，防止高并发多次查询数据库，锁不住的结果
        // 设置七天过期，防止缓存雪崩
        stringRedisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(map), 7, TimeUnit.DAYS);
        return map;
    }

    /**
     * 用于查找在指定菜单集合中，父菜单ID为parent_cid的菜单
     *
     * @param categoryEntityList
     * @param parent_cid
     * @return
     */
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> categoryEntityList, Long parent_cid) {
        return categoryEntityList.stream().filter(item -> item.getParentCid().equals(parent_cid)).collect(Collectors.toList());
        // return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    /**
     * 递归查找当前菜单的父菜单
     *
     * @param catelogId
     * @return
     */
    private List<Long> findParentCatelogPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentCatelogPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找从所有菜单中返回当前菜单的子菜单
     *
     * @param root 当前菜单
     * @param all  所有菜单
     * @return 当前菜单的子菜单
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map((categoryEntity) -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                })
                .sorted((menu1, menu2) -> (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return children;
    }

}